<template>
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="550"
    :width="650"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Tabs v-model:activeKey="activeKey">
      <TabPane key="1" :tab="t('routes.demo.workFlow.startFlow.property')">
        <BasicForm @register="registerForm">
          <template #code="{ model }">
            <Input
              v-model:value="model['code']"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.codePlaceholder')"
              readOnly
            >
              <template #addonAfter>
                <Tooltip
                  :title="t('routes.demo.workFlow.startFlow.propertySet.selectFlowTemplate')"
                >
                  <a-button @click="handleSelectFlow" :disabled="isUpdated">...</a-button>
                </Tooltip>
              </template>
            </Input>
          </template>
          <template #overdueTime="{ model }">
            <Row>
              <Col :span="8">
                <Input
                  v-model:value="model['overdueTimeDay']"
                  :placeholder="
                    t('routes.demo.workFlow.startFlow.propertySet.overdueTimePlaceholder')
                  "
                  :disabled="isUpdated || model['overDueFormHandleWay'] === '2'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.days') }}</span>
              </Col>
              <Col :span="8">
                <Input
                  v-model:value="model['overdueTimeHour']"
                  :placeholder="
                    t('routes.demo.workFlow.startFlow.propertySet.overdueTimePlaceholder')
                  "
                  :disabled="isUpdated || model['overDueFormHandleWay'] === '2'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.hours') }}</span>
              </Col>
            </Row>
          </template>
        </BasicForm>
      </TabPane>
      <TabPane key="2" :tab="t('routes.demo.workFlow.startFlow.step')" forceRender>
        <!-- 步骤表格 -->
        <BasicTable @register="registerTable" :dataSource="stepList">
          <!-- 负责人处理方式 -->
          <template #process="{ text: process }">
            <span>{{
              process === 7
                ? t('routes.demo.workFlow.flowModelPage.selectPrincipal')
                : t('routes.demo.workFlow.flowModelPage.selectPrincipalInTemplate')
            }}</span>
          </template>
          <!-- 超期消息处理方式 -->
          <template #msgOverTimeHandWay="{ text: msgOverTimeHandWay }">
            <span>{{
              msgOverTimeHandWay === '1'
                ? t('routes.demo.workFlow.way3')
                : t('routes.demo.workFlow.way4')
            }}</span>
          </template>
          <!-- 完成消息处理方式 -->
          <template #msgFinishWay="{ text: msgFinishWay }">
            <span>{{
              msgFinishWay === '1' ? t('routes.demo.workFlow.way3') : t('routes.demo.workFlow.way4')
            }}</span>
          </template>
        </BasicTable>
        <!-- 单步步骤表单 -->
        <Form
          :model="currentStepInfo"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 18, offset: 1 }"
        >
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.name')">
            <Input
              v-model:value="currentStepInfo.actor"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.namePlaceholder')"
              readonly
            >
              <!-- <template #suffix>
                <Icon icon="ion:ios-close-outline" @click="clearName" />
              </template> -->
              <template #addonAfter>
                <a-button
                  type="primary"
                  @click="handleAdjust"
                  :disabled="currentStepInfo.process === 1 || isStart || isUpdated"
                  >{{ t('routes.demo.workFlow.startFlow.stepSet.adjustStepPrincipal') }}</a-button
                >
              </template>
            </Input>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.overdueTime')">
            <Row>
              <Col :span="8">
                <Input
                  v-model:value="currentStepInfo.stepOverDays"
                  :placeholder="t('routes.demo.workFlow.startFlow.stepSet.overdueTimePlaceholder')"
                  @change="changeStep(currentStepInfo.stepOverDays, '天')"
                  :disabled="isStart || isUpdated"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.days') }}</span>
              </Col>
              <Col :span="8">
                <Input
                  v-model:value="currentStepInfo.stepOverHours"
                  :placeholder="t('routes.demo.workFlow.startFlow.stepSet.overdueTimePlaceholder')"
                  @change="changeStep(currentStepInfo.stepOverHours, '小时')"
                  :disabled="isStart || isUpdated"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.hours') }}</span>
              </Col>
            </Row>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.workDescription')">
            <Textarea
              v-model:value="currentStepInfo.description"
              @change="changeStep(currentStepInfo.description, '工作说明')"
              :disabled="isStart || isUpdated"
            />
          </FormItem>
          <FormItem
            :label="t('routes.demo.workFlow.startFlow.stepSet.stepTable.overdueMessageReceiver')"
          >
            <Select
              v-model:value="currentStepInfo.overTimeMsgReciver"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.adjustMessageReceiver')"
              @change="changeStep(currentStepInfo.overTimeMsgReciver, '超期消息接收人')"
              :disabled="currentStepInfo.msgOverTimeHandWay === '2' || isStart || isUpdated"
            >
              <SelectOption v-for="item in userList" :key="item.id" :value="item.id">{{
                item.name
              }}</SelectOption>
            </Select>
          </FormItem>
          <FormItem
            :label="t('routes.demo.workFlow.startFlow.stepSet.stepTable.finishMessageReceiver')"
          >
            <Select
              v-model:value="currentStepInfo.msgFinsihReciver"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.adjustMessageReceiver')"
              @change="changeStep(currentStepInfo.msgFinsihReciver, '完成消息接收人')"
              :disabled="currentStepInfo.msgFinishWay === '2' || isStart || isUpdated"
            >
              <SelectOption v-for="item in userList" :key="item.id" :value="item.id">{{
                item.name
              }}</SelectOption>
            </Select>
          </FormItem>
        </Form>
      </TabPane>
      <TabPane key="3" :tab="t('routes.demo.workFlow.startFlow.object')">
        <BasicTable @register="registerObjTable" :dataSource="objList">
          <template #toolbar>
            <a-button
              v-show="flowStatus === '图档'"
              type="primary"
              @click="addDocument"
              :disabled="isUpdated ? checkBit(stepSetting, 1) : false"
            >
              {{ t('routes.demo.workFlow.startFlow.addDocument') }}
            </a-button>
            <a-button
              v-show="flowStatus === '零件'"
              type="primary"
              @click="addPart"
              :disabled="isUpdated ? checkBit(stepSetting, 1) : false"
            >
              添加零件
            </a-button>
            <!-- <a-button type="primary" @click="addForm" :disabled="checkBit(stepSetting, 1)">
              {{ t('routes.demo.workFlow.startFlow.addForm') }}
            </a-button> -->
          </template>
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  label: t('common.delete'),
                  onClick: DeleteObj.bind(null, record),
                  disabled: isUpdated ? checkBit(stepSetting, 1) : false,
                },
              ]"
            />
          </template>
        </BasicTable>
      </TabPane>
      <TabPane key="4" :tab="t('routes.demo.workFlow.startFlow.referenceDocument')">
        <BasicTable @register="registerDocTable" :dataSource="docList">
          <template #toolbar>
            <a-button
              type="primary"
              @click="addReferenceDoc"
              :disabled="isUpdated ? checkBit(stepSetting, 3) : false"
            >
              {{ t('common.add') }}
            </a-button>
          </template>
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  icon: 'ion:ios-eye',
                  label: t('common.view'),
                  onClick: handleView.bind(null, record),
                },
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  label: t('common.delete'),
                  onClick: handleDelete.bind(null, record),
                },
                {
                  icon: 'ion:download-outline',
                  label: t('common.download'),
                  onClick: handleDownload.bind(null, record),
                  disabled: isUpdated ? checkBit(stepSetting, 4) : false,
                },
              ]"
            />
          </template>
        </BasicTable>
      </TabPane>
    </Tabs>
  </BasicModal>

  <!-- 新增图档 -->
  <selectDocModal
    @register="registerSelectDocModal"
    @success="handleSelectDocModalSuccess"
    @successDoc="handleFormModalSuccess"
  />

  <!-- 新增零件 -->
  <partManagerModal @register="registerPartManagerModal" @success="handleSelectPartModalSuccess" />

  <!-- 选择流程窗口 -->
  <BasicModal
    :destroyOnClose="true"
    :minHeight="200"
    :width="1000"
    @register="registerSelectFlow"
    @ok="handleSelectionSubmit"
    @cancel="handleSelectionCancel"
  >
    <BasicTable
      @register="registerSelectionTable"
      :dataSource="wkfList"
      :rowSelection="{
        type: 'radio',
        selectedRowKeys: wkfSelectedRowKeys,
        onChange: wkfSelectChange,
      }"
    />
  </BasicModal>
  <!-- 调整步骤负责人窗口 -->
  <BasicModal
    :destroyOnClose="true"
    :minHeight="200"
    :width="500"
    @register="registerAdjust"
    @ok="handleAdjustSubmit"
    @cancel="handleAdjustCancel"
  >
    <InputSearch
      :placeholder="t('routes.demo.workFlow.initiateFlowPage.search')"
      style="width: 200px; margin-bottom: 10px"
      :allowClear="true"
      @change="changeSearch"
      @search="psnSearch"
    />
    <BasicTable @register="registerAdjustTable" :data-source="userList" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import {
    Tabs,
    TabPane,
    Input,
    Row,
    Col,
    Tooltip,
    Form,
    FormItem,
    Select,
    SelectOption,
  } from 'ant-design-vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  import Icon from '/@/components/Icon';
  import throttle from 'lodash/throttle';

  import selectDocModal from '/@/views/demo/documentManager/components/selectDocModal.vue';
  import partManagerModal from '/@/views/demo/partManager/components/partManagerModal.vue';

  import {
    GetWorkflowsListUseType,
    getStepApi,
    getCodeNameApi,
    getNewFlowApi,
  } from '/@/api/demo/flow';
  import { Getallpersondto } from '/@/api/demo/system';
  import {
    downloadFile,
    GetIsInWorkflow,
    GetWorkflowinsDetailsInfo,
    UpdateObjectList,
    GetPublishFileMsg,
  } from '/@/api/demo/document';
  import { GetPartWfs } from '/@/api/demo/partManager';
  import { handleBrowseFile } from '/@/utils/demo/preview';

  import {
    getBasicInfo,
    getFlowStepColumns,
    getAdjustColumns,
    getFlowObjColumns,
    getFlowDocColumns,
    getSelectionColumns,
  } from './flowData';

  const InputSearch = Input.Search;
  const Textarea = Input.TextArea;

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const useCommonStore = useUserStore();
  const activeKey = ref<string>('1'); // 控制Tabs组件的激活项
  const currentStepIndex = ref<number>(0); // 当前步骤索引
  const wkfSelectedRowKeys = ref<any>([]); // 流程模板选择id
  const wkfSelectedRow = ref<any>([]); // 流程模板选择数据
  // 项目管理信息
  const someInfos = ref<any>({
    projectid: '',
    projectName: '',
    taskName: '',
  });
  // 记录流程类型
  const flowType = ref<string>('');
  // 记录表单id
  const formID = ref<string>('');
  // 记录流程状态
  const flowStatus = ref<string>('');
  // 对象列表
  const objList = ref<any>([]);
  // 参考图档
  const docList = ref<any>([]);
  // 流程模板列表
  const wkfList = ref<any>([]);
  // 步骤列表
  const stepList = ref<any>([]);
  // 流程信息
  const wkfInfos = ref<any>({});
  // 记录当前文件信息
  const currentSelectFile = ref<any>({});
  // 记录当前步骤信息
  const currentStepInfo = ref<any>({});
  // 获取人员列表
  const userList = ref<any>([]);
  // 记录当前步骤负责人
  const stepCharge = ref<any>({});
  // 记录当前步骤负责人索引
  const userIndex = ref<any>(0);
  const currentSelectWkf = ref<any>({});
  // 获取步骤控制
  const stepSetting = ref<any>('');
  // 查看是否为开始
  const isStart = ref<boolean>(true);
  const isUpdated = ref<boolean>(false); // 是否更新
  const flowDetail = ref<any>({}); // 流程详情
  const isVersion = ref<string>('0'); // 是否创建新版本
  const isMessage = ref<string>('0'); // 是否发送消息

  // 提交
  const handleSubmit = async () => {
    if (isUpdated.value) {
      // 更新
      const { workflowid, step } = flowDetail.value;

      const currentPdmList = objList.value
        .filter((item) => item.stepInstanceId === step)
        .map((item) => ({
          target: item.id,
          version: item.version,
        }));

      const currentDocList = (docList.value || [])
        .filter((item) => item.stepInstanceId === step)
        .map((item) => ({
          target: item.id,
          version: item.version,
        }));

      const params = {
        workflowInstancesId: workflowid,
        currentStep: step,
        listpdmr: currentPdmList,
        descriptNote: currentDocList.length > 0 ? currentDocList : null,
      };

      try {
        setModalProps({ confirmLoading: true });
        await UpdateObjectList(params);
        createMessage.success('流程修改成功');
        await handleCancel();
      } catch (error) {
        setModalProps({ confirmLoading: false });
        console.error('流程修改失败:', error);
      }
    } else {
      // 新增
      // 过滤掉 listssdto 为 null 的步骤
      const filteredSteps = stepList.value.filter((step) => step.listssdto !== null);

      // 分组步骤
      const groupSteps = (steps) => {
        const groups = [];

        steps.forEach((step) => {
          let groupFound = false;
          for (const group of groups) {
            if (group.some((item) => step.listssdto.some((dto) => dto.source === item.id))) {
              group.push(step);
              groupFound = true;
              break;
            }
          }

          if (!groupFound) {
            groups.push([step]);
          }
        });

        return groups;
      };

      // 校验每组的逻辑关系和 actor
      const validateGroup = (group) => {
        const logicOrSteps = group.filter((step) => step.routerOnEntry === '0');
        const logicAndSteps = group.filter((step) => step.routerOnEntry === '1');

        // 逻辑或关系（routerOnEntry = 0）：只要一个 actor 有数据即可
        const hasLogicOrActor = logicOrSteps.some((step) => step.actor);

        // 逻辑与关系（routerOnEntry = 1）：所有 actor 必须有数据
        const allLogicAndActorsFilled = logicAndSteps.every((step) => step.actor);

        if (logicOrSteps.length > 0 && !hasLogicOrActor) {
          createMessage.error('逻辑或组中必须至少有一个步骤的 actor 有数据。');
          throw new Error('逻辑或组中必须至少有一个步骤的 actor 有数据。');
        }

        if (logicAndSteps.length > 0 && !allLogicAndActorsFilled) {
          createMessage.error('逻辑与组中所有步骤的 actor 必须有数据。');
          throw new Error('逻辑与组中所有步骤的 actor 必须有数据。');
        }

        // 如果同时有逻辑或和逻辑与，则逻辑与必须满足 actor 有数据
        if (logicOrSteps.length > 0 && logicAndSteps.length > 0 && !allLogicAndActorsFilled) {
          createMessage.error('逻辑与组中的 actor 必须有数据。');
          throw new Error('逻辑与组中的 actor 必须有数据。');
        }

        return true;
      };

      // 执行分组并校验
      const groupedSteps = groupSteps(filteredSteps);
      for (const group of groupedSteps) {
        try {
          validateGroup(group);
          // console.log(`组 ${group.map((step) => step.id).join(', ')} 校验通过`);
        } catch (error) {
          // console.error(`组 ${group.map((step) => step.id).join(', ')} 校验失败: ${error.message}`);
          return; // 一旦校验失败，停止执行后续操作
        }
      }

      // 验证整理接口传参数据
      for (const step of stepList.value) {
        if (!step.actor?.trim() && step.unSelected === '0') {
          return createMessage.error(`步骤：${step.id} 未指定执行人`);
        }
      }

      // 组织新建流程数据
      const params = {
        workflowType: flowType.value.split('流程')[0], // 创建的流程类型
        workflowInstancesid: wkfInfos.value.id, // 流程实例id
        workflowInstancesName:
          objList.value.length == 1 ? flowType.value : `${flowType.value}-多对象`, // 创建的流程类型
        actor: currentSelectWkf.value.actor, // 执行人
        workflow: currentSelectWkf.value.wfid, // 所选流程类型id
        remark: currentSelectWkf.value.remark, // 备注
        creator: useCommonStore.userInfo?.userId, // 创建人
        rebacksetting: currentSelectWkf.value.htfs, // 回退方式0模板1自由
        bzxzSelect: currentSelectWkf.value.htfsselected, // 步骤选择0否1是
        overTimeDay: currentSelectWkf.value.overDueForm?.day, // 超时天数
        overTimeHour: currentSelectWkf.value.overDueForm?.hour, // 超时小时
        overTimeMsgReciver: currentSelectWkf.value.messageForm?.receiver, // 超时消息接收人
        liststi: stepList.value.map((item) => ({
          workflowID: item.id, // 流程id
          actor: item.actor, // 执行人
          description: item.description, // 描述
          overTimeDay: item.stepOverDays, // 超时天数
          overTimeHour: item.stepOverHours, // 超时小时
          overTimeMsgReciver: item.overTimeMsgReciver, // 超时消息接收人
          overTimesFinishMsgReciver: item.msgFinsihReciver, // 超时完成消息接收人
        })), // 流程步骤
        listpdmr: objList.value.map((item) => ({
          target: item.id,
          version: item.version,
        })), // 对象
        descriptNote: docList.value.map((item) => ({
          target: item.id,
          version: item.version,
        })), // 参考图档
        isUpGrade: isVersion.value, // 是否升级 0否1是
        isSendMsg: isMessage.value, // 是否发送消息 0否1是
      };
      if (formID.value != '') {
        params.listpdmr.push({
          target: formID.value,
          version: 1,
        });
      }

      try {
        setModalProps({ confirmLoading: true });
        await getNewFlowApi(params);
        createMessage.success(t('routes.demo.workFlow.initiateFlowPage.createSuccess'));
        await handleCancel();
      } catch (error) {
        setModalProps({ confirmLoading: false });
        console.error('流程创建失败:', error);
      }
    }
  };

  // 取消
  const handleCancel = async () => {
    activeKey.value = '1';
    closeModal();
  };

  // 步骤控制
  const checkBit = (str, index) => {
    if (index < 1 || index > str.length) {
      throw new Error('索引超出范围');
    }
    return str.charAt(index - 1) === '0';
  };

  // 选择流程表格
  const [registerSelectionTable] = useTable({
    columns: getSelectionColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    striped: false,
    rowKey: 'wfid',
  });
  // 选择流程表格选中事件
  const wkfSelectChange = (selectedRowKeys, selectedRows) => {
    wkfSelectedRowKeys.value = selectedRowKeys;
    wkfSelectedRow.value = selectedRows;
    currentSelectWkf.value = selectedRows[0];
    stepList.value = [];
  };
  // 选择流程模板
  const [registerSelectFlow, { openModal: openSelectFlowModal, closeModal: closeSelectFlowModal }] =
    useModal();

  const handleSelectFlow = async () => {
    // 根据流程类型筛选流程模板
    wkfList.value = await GetWorkflowsListUseType(flowType.value);
    openSelectFlowModal(true);
  };

  // 处理流程模板格式
  const setFlowTemp = async (row) => {
    if (!row || typeof row !== 'object') return null;

    const newRow = {
      name: currentSelectFile.value ? row.type : `${row.type ?? '通用流程'}-多对象`,
      code: row.wfid ?? '',
      startTime: moment(new Date()),
      principal: row.actor ?? '',
      stepSelect: row.bzxzselected === '1',
      backMethod: row.htfsselected ?? '',
      overdueTimeDay: row.overDueForm?.day ?? 0,
      overdueTimeHour: row.overDueForm?.hour ?? 0,
      overdueMessageReceiver: row.messageForm?.receiver ?? '',
      bzxz: row.bzxz ?? '', // 步骤选择
      htfs: row.htfs ?? '', // 回退方式
      overDueFormHandleWay: row.overDueForm?.handleWay ?? '', // 超时处理方式
      messageFormHandleWay: row.messageForm?.handleWay ?? '', // 消息处理方式
    };

    return newRow;
  };

  // 选择流程模板成功
  const handleSelectionSubmit = async () => {
    const newData = await setFlowTemp(wkfSelectedRow.value[0]);
    await setFlowTempValue(newData);
    await handleSteps(); // 获取步骤
    handleSelectionCancel();
  };
  // 选择流程模板取消
  const handleSelectionCancel = async () => {
    wkfList.value = [];
    closeSelectFlowModal();
  };

  // 对象图档
  const [registerSelectDocModal, { openModal: openSelectDocModal }] = useModal();
  // 对象零件
  const [registerPartManagerModal, { openModal: openSelectPartModal }] = useModal();

  // 添加对象表单
  const [registerFormModal, { openModal: openFormModal }] = useModal();

  // 添加对象图档成功
  const handleSelectDocModalSuccess = async (data) => {
    const { oId, checkOutPerson, state, id } = data;
    const isFlow = await GetIsInWorkflow(oId); // 统一获取流程状态

    const showError = (message) => {
      createMessage.error(message);
      return false;
    };

    switch (flowType.value) {
      case '检出流程':
        if (state !== '8') return showError('只能添加状态为生效的对象');
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;

      case '检入流程':
        if (checkOutPerson !== useCommonStore.userInfo?.userId)
          return showError('只能执行检出人为自己的对象');
        if (state !== '1') return showError('只能添加状态为检出的对象');
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;

      case '发布流程':
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;

      case '废止流程':
      case '借阅流程':
        if (state !== '8') return showError('只能添加状态为生效的对象');
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;
    }
    if (flowType.value == '发布流程') {
      const params = {
        wkfId: isUpdated.value ? flowDetail.value.workflowid : wkfInfos.value.id,
        Oid: data.oId,
        Version: data.version,
        DocName: data.filename,
      };
      const result = await GetPublishFileMsg(params);
      if (result) {
        const newItem = { ...data }; // 浅拷贝，够用了（也可以用 lodash 深拷贝）
        if (isUpdated.value) {
          newItem.stepInstanceId = flowDetail.value.step;
        }
        if (!objList.value.find((item) => item.id === id)) {
          objList.value = [...objList.value, newItem];
        }
      }
    } else {
      const newItem = { ...data }; // 浅拷贝，够用了（也可以用 lodash 深拷贝）
      if (isUpdated.value) {
        newItem.stepInstanceId = flowDetail.value.step;
      }
      if (!objList.value.find((item) => item.id === id)) {
        objList.value = [...objList.value, newItem];
      }
    }
  };

  // 添加零件成功
  const handleSelectPartModalSuccess = async (data) => {
    const { oId, checkOutPerson, state, id } = data;
    const isFlow = await GetIsInWorkflow(oId); // 统一获取流程状态

    const showError = (message) => {
      createMessage.error(message);
      return false;
    };

    switch (flowType.value) {
      case '检出流程':
        if (state !== '1') return showError('只能添加状态为生效的对象');
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;

      case '检入流程':
        if (checkOutPerson !== useCommonStore.userInfo?.userId)
          return showError('只能执行检出人为自己的对象');
        if (state !== '2') return showError('只能添加状态为检出的对象');
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;

      case '发布流程':
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;

      case '废止流程':
      case '借阅流程':
        if (state !== '1') return showError('只能添加状态为生效的对象');
        if (!isFlow) return showError('对象已在流程中, 无法添加');
        break;
    }
    if (flowType.value == '发布流程') {
      const params = {
        wkfId: isUpdated.value ? flowDetail.value.workflowid : wkfInfos.value.id,
        Oid: data.oId,
        Version: data.version,
        DocName: data.filename,
      };
      const result = await GetPublishFileMsg(params);
      if (result) {
        const newItem = { ...data }; // 浅拷贝，够用了（也可以用 lodash 深拷贝）
        if (isUpdated.value) {
          newItem.stepInstanceId = flowDetail.value.step;
        }
        if (!objList.value.find((item) => item.id === id)) {
          objList.value = [...objList.value, newItem];
        }
      }
    } else {
      const newItem = { ...data }; // 浅拷贝，够用了（也可以用 lodash 深拷贝）
      if (isUpdated.value) {
        newItem.stepInstanceId = flowDetail.value.step;
      }
      if (!objList.value.find((item) => item.id === id)) {
        objList.value = [...objList.value, newItem];
      }
    }
  };

  // 添加参考图档成功
  const handleFormModalSuccess = (data) => {
    docList.value ??= [];
    const newItem = { ...data }; // 浅拷贝，够用了（也可以用 lodash 深拷贝）
    if (isUpdated.value) {
      newItem.stepInstanceId = flowDetail.value.step;
    }
    const isExist = docList.value.find((item) => item.id === data.id);
    if (!isExist) {
      docList.value = [...docList.value, newItem];
    }
  };

  // 新增图档
  const addDocument = () => {
    openSelectDocModal(true, { type: '新建流程对象' });
  };
  // 新增零件
  const addPart = () => {
    openSelectPartModal(true, { isFrom: '新建流程对象' });
  };
  // 删除对象
  const DeleteObj = (record: Recordable) => {
    let firstName = record.stepInstanceId.split('.')[1];
    if (firstName === '开始') {
      createMessage.error('初始流程对象不能删除');
      return;
    }
    if (isUpdated.value && flowDetail.value.step !== record.stepInstanceId) {
      createMessage.error('非当前流程步骤，对象不能删除');
      return;
    }

    objList.value = objList.value.filter((item) => item.id !== record.id);
  };

  // 新增参考文档
  const addReferenceDoc = () => {
    openSelectDocModal(true, { type: '新增参考文档' });
  };

  // 查看
  const handleView = async (record: Recordable) => {
    await handleBrowseFile(record, '新建流程');
  };
  // 删除
  const handleDelete = (record: Recordable) => {
    if (isUpdated.value && flowDetail.value.step !== record.stepInstanceId) {
      createMessage.error('非当前流程步骤，参考文档不能删除');
      return;
    }
    const index = docList.value.findIndex((item) => item.id === record.id);
    docList.value.splice(index, 1);
  };
  // 下载
  const handleDownload = throttle((record: Recordable) => {
    downloadFile(record.id, record.version, record.filename).then(() => {
      createMessage.success(t('common.downLoadSuccess'));
    });
  }, 3000);

  // 参考文档
  const [registerDocTable] = useTable({
    columns: getFlowDocColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    rowKey: 'id',
    canResize: true,
    scroll: { y: 300 },
    actionColumn: {
      width: 200,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 对象表格
  const [registerObjTable] = useTable({
    columns: getFlowObjColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    rowKey: 'id',
    canResize: true,
    scroll: { y: 300 },
    actionColumn: {
      width: 200,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 步骤表格
  const [registerTable] = useTable({
    columns: getFlowStepColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    canResize: false,
    rowKey: 'shortId',
    customRow: (record, index) => {
      return {
        onClick: () => {
          // 打开调整弹窗
          currentStepIndex.value = index;
          currentStepInfo.value.shortId = record.shortId;
          currentStepInfo.value.actor = record.actor;
          currentStepInfo.value.stepOverDays = record.stepOverDays;
          currentStepInfo.value.stepOverHours = record.stepOverHours;
          currentStepInfo.value.description = record.description;
          currentStepInfo.value.msgFinsihReciver = record.msgFinsihReciver;
          currentStepInfo.value.overTimeMsgReciver = record.overTimeMsgReciver;
          currentStepInfo.value.process = record.process; // 负责人处理方式
          currentStepInfo.value.msgOverTimeHandWay = record.msgOverTimeHandWay; // 超期消息处理方式
          currentStepInfo.value.msgFinishWay = record.msgFinishWay; // 完成消息处理方式
          isStart.value = record.name == '开始';
        },
      };
    },
    //改变 当负责人代号为空的那一行字体颜色为红色，负责人代号不为空字体颜色为黑色，选中当前行背景色改为蓝色
    rowClassName: (record: any, index: number) => {
      let classStr = '';
      let actor = record.actor.replace(/\s*/, '');
      // 如果负责人代号为空
      if (!actor) {
        // 如果该行未被选中
        if (record.unSelected == '1') {
          classStr += 'rowClassSelected';
        } else {
          classStr += 'rowClass2';
        }
      }
      // 如果该行被选中
      if (index === currentStepIndex.value) {
        classStr += ' rowClass';
      }
      return classStr;
    },
  });

  const clearName = () => {
    let obj = stepList.value.find((item) => item.shortId == currentStepInfo.value.shortId);
    if (obj) {
      obj.actor = '';
    }
  };
  // 调整步骤负责人
  const [registerAdjust, { openModal: openAdjustModal, closeModal: closeAdjustModal }] = useModal();
  // 调整步骤负责人表格
  const [registerAdjustTable] = useTable({
    columns: getAdjustColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    striped: false,
    rowKey: 'id',
    customRow: (record) => {
      return {
        onClick: () => {
          stepCharge.value = record;
          userIndex.value = record.id;
        },
      };
    },
    rowClassName: (record: any) => {
      return record.id === userIndex.value ? 'clickRowStyle' : '';
    },
  });

  const handleAdjust = () => {
    openAdjustModal(true);
  };
  const changeStep = (e: any, type: string) => {
    const obj = stepList.value.find((o) => o.shortId === currentStepInfo.value.shortId);
    if (!obj) return;

    const fieldMap: Record<string, string> = {
      天: 'stepOverDays',
      小时: 'stepOverHours',
      工作说明: 'description',
      超期消息接收人: 'msgFinsihReciver',
      完成消息接收人: 'overTimeMsgReciver',
    };

    if (fieldMap[type]) {
      obj[fieldMap[type]] = e;
    }
  };

  const handleAdjustSubmit = () => {
    if (Object.keys(stepCharge.value).length != 0) {
      let obj = stepList.value.find((o) => o.shortId == currentStepInfo.value.shortId);
      if (obj) {
        obj.actor = '@psn@' + stepCharge.value.id;
        currentStepInfo.value.actor = '@psn@' + stepCharge.value.id;
      }
    }
    handleAdjustCancel();
  };
  const handleAdjustCancel = () => {
    stepCharge.value = {};
    closeAdjustModal();
  };

  // 基本属性
  const [registerForm, { setFieldsValue: setFlowTempValue, updateSchema: updateFlowTempSchema }] =
    useForm({
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      schemas: getBasicInfo(),
      showActionButtonGroup: false,
    });

  // 初始化弹窗
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    userList.value = await Getallpersondto({});
    // record当前文档信息，type流程类型，selectedFiles 批量对象，projectid项目id，projectName项目名称，taskName任务名称，formId表单id,state流程状态分为图档或者零件, ReleaseProcessID发布流程ID, createNewVersion 是否创建新版本, sendMessage 是否发送消息
    const {
      record,
      type,
      selectedFiles,
      projectid,
      projectName,
      taskName,
      formId,
      state,
      isUpdate,
      ReleaseProcessID,
      createNewVersion,
      sendMessage,
    } = data;
    // 流程状态 '零件'/ '图档'
    flowStatus.value = state;
    isUpdated.value = isUpdate;
    if (isUpdate) {
      // 更新流程
      flowDetail.value = record;
      // 查看流程信息
      const res = await GetWorkflowinsDetailsInfo('', record.workflowid, '');
      setFlowTempValue(res.basicInfo);
      // 获取步骤信息
      updateFlowTempSchema([
        { field: 'name', componentProps: { disabled: true } },
        { field: 'code', componentProps: { disabled: true } },
        { field: 'startTime', componentProps: { disabled: true } },
        { field: 'principal', componentProps: { disabled: true } },
        { field: 'stepSelect', componentProps: { disabled: true } },
        { field: 'backMethod', componentProps: { disabled: true } },
        { field: 'overdueTime', componentProps: { disabled: true } },
        { field: 'overdueTimeDay', componentProps: { disabled: true } },
        { field: 'overdueTimeHour', componentProps: { disabled: true } },
        { field: 'overdueMessageReceiver', componentProps: { disabled: true } },
      ]);
      stepList.value = res.stepList;
      // 记录当前步骤
      currentStepInfo.value.shortId = stepList.value[0].shortId;
      currentStepInfo.value.actor = stepList.value[0].actor;
      currentStepInfo.value.stepOverDays = stepList.value[0].stepOverDays;
      currentStepInfo.value.stepOverHours = stepList.value[0].stepOverHours;
      currentStepInfo.value.description = stepList.value[0].description;
      currentStepInfo.value.msgFinsihReciver = stepList.value[0].msgFinsihReciver;
      currentStepInfo.value.overTimeMsgReciver = stepList.value[0].overTimeMsgReciver;
      currentStepInfo.value.process = stepList.value[0].process; // 负责人处理方式
      currentStepInfo.value.msgOverTimeHandWay = stepList.value[0].msgOverTimeHandWay; // 超期消息处理方式
      currentStepInfo.value.msgFinishWay = stepList.value[0].msgFinishWay; // 完成消息处理方式
      // 记录第一步步骤，控制对象，参考文档
      stepSetting.value = record.wfModelData.attrstr;
      isStart.value = stepList.value[0].name == '开始';
      // 获取对象信息
      objList.value = res.objList;
      // 获取参考文档
      docList.value = res.docList;
      flowType.value = record.workflow.split('-')[0]; // 流程类型
    } else {
      isVersion.value = createNewVersion ?? '0';
      isMessage.value = sendMessage ?? '0';
      currentSelectFile.value = record; // 当前选中的文件
      flowType.value = type; // 流程类型
      someInfos.value = { projectid, projectName, taskName }; // 项目管理信息
      formID.value = formId; // 表单id
      // 获取流程信息
      const typeName = type.split('流程')[0];
      // 获取流程信息
      if (type == '发布流程') {
        wkfInfos.value.id = ReleaseProcessID;
      } else {
        wkfInfos.value =
          state === '图档'
            ? await getCodeNameApi(typeName, record?.filename, record?.version)
            : await GetPartWfs(typeName, record?.filename, record?.version, record.oId);
      }

      // 单对象流程
      const handleSingleFlow = async () => {
        // 对象转数组,给对象赋值
        objList.value = [{ ...record }];
        // 根据流程类型筛选流程模板
        wkfList.value = await GetWorkflowsListUseType(type);
        // 符合条件的流程模板只有一个，默认取第一个
        if (wkfList.value.length >= 1) {
          const data = await setFlowTemp(wkfList.value[0]);
          wkfSelectedRowKeys.value = [wkfList.value[0].wfid];
          currentSelectWkf.value = wkfList.value[0];
          await setFlowTempValue(data);
          await handleSteps(); // 获取步骤
        }
      };

      // 批量对象流程
      const handleBatchFlow = async () => {
        // 给对象赋值
        objList.value = selectedFiles;
        // 根据流程类型筛选流程模板
        wkfList.value = await GetWorkflowsListUseType(type);
        // 符合条件的流程模板只有一个，默认取第一个
        if (wkfList.value.length >= 1) {
          const data = await setFlowTemp(wkfList.value[0]);
          wkfSelectedRowKeys.value = [wkfList.value[0].wfid];
          currentSelectWkf.value = wkfList.value[0];
          await setFlowTempValue(data);
          await handleSteps(); // 获取步骤
        }
      };

      // 如果record存在，则执行handleSingleFlow()函数
      if (record) {
        handleSingleFlow();
      } else {
        // 否则执行handleBatchFlow()函数
        handleBatchFlow();
      }
    }
  });

  // 获取步骤
  const handleSteps = async () => {
    const res: any = await getStepApi(wkfSelectedRowKeys.value[0]);
    if (!res || !Array.isArray(res.liststdto) || res.liststdto.length <= 1) {
      return createMessage.error(t('routes.demo.workFlow.initiateFlowPage.noStep'));
    }
    // 渲染步骤表格
    stepList.value = res.liststdto;
    if (!stepList.value[0].actor?.trim()) {
      stepList.value[0].actor = `@psn@${useCommonStore.userInfo?.userId}`;
    }
    // 记录当前步骤
    currentStepInfo.value.shortId = stepList.value[0].shortId;
    currentStepInfo.value.actor = stepList.value[0].actor;
    currentStepInfo.value.stepOverDays = stepList.value[0].stepOverDays;
    currentStepInfo.value.stepOverHours = stepList.value[0].stepOverHours;
    currentStepInfo.value.description = stepList.value[0].description;
    currentStepInfo.value.msgFinsihReciver = stepList.value[0].msgFinsihReciver;
    currentStepInfo.value.overTimeMsgReciver = stepList.value[0].overTimeMsgReciver;
    currentStepInfo.value.process = stepList.value[0].process; // 负责人处理方式
    currentStepInfo.value.msgOverTimeHandWay = stepList.value[0].msgOverTimeHandWay; // 超期消息处理方式
    currentStepInfo.value.msgFinishWay = stepList.value[0].msgFinishWay; // 完成消息处理方式
    // 记录第一步步骤，控制对象，参考文档
    stepSetting.value = stepList.value[0].settingstr;
    console.log(stepSetting.value, 123);
    isStart.value = stepList.value[0].name == '开始';
  };
</script>

<style lang="less" scoped>
  ::v-deep(.rc-virtual-list-scrollbar-thumb) {
    visibility: hidden !important;
  }

  ::v-deep(.ant-input-group-addon) {
    background-color: #fff !important;
    border: 0 solid #d9d9d9 !important;
  }

  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }

  ::v-deep(.clickRowStyle) {
    background-color: #e6f7ff !important;
  }

  ::v-deep(.rowClassSelected) {
    color: orange !important;
  }

  ::v-deep(.rowClass) {
    background-color: #e6f7ff !important;
  }

  ::v-deep(.rowClass2) {
    color: red !important;
  }
</style>
